package cn.gpdi.framework.interceptor;

import cn.gpdi.framework.annotation.FwIsOpenRequest;
import cn.gpdi.framework.pojo.FwLoginException;
import cn.gpdi.framework.pojo.FwTextTransObject;
import cn.gpdi.framework.util.CommUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by 司徒鑫(QQ:156845600) on 2018/4/16.
 */
public class SysInterceptor implements HandlerInterceptor {

    private static final Log log = LogFactory.getLog(SysInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.debug("preHandle...");

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "1728000");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");


        if (request.getMethod().equals("OPTIONS")   //跨域中的前置请求
               // || "0".equals(CommUtil.getPropVal("LOGIN_CHECK"))   //开发环境、生产环境差异配置
                || ((HandlerMethod) handler).getMethod().getAnnotation(FwIsOpenRequest.class) != null//方法备注为FwIsOpenRequest
                ) {
            return true;
        }else {
            String fw_service=request.getParameter("fw_service");
            String fw_method=request.getParameter("fw_method");
            if(!CommUtil.isEmpty(fw_service)&&!CommUtil.isEmpty(fw_method)){
                return   AopUtils.getTargetClass(CommUtil.getBean(fw_service)).getDeclaredMethod(fw_method, FwTextTransObject.class)!=null;
            }else {
                //登陆判断
                if(request.getSession().getAttribute("LOGIN")!=null){
                    return true;
                }
                throw new FwLoginException("尚未登录，跳转到登录页面");
            }
        }
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object
            o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse httpServletResponse, Object
            o, Exception e) throws Exception {

    }
}